#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
#include <unistd.h>
#include <string.h>

using namespace std;

int main()
{
    const char * filename = "./testFifo";

    /* 判断管道文件是否存在 */
    int temp = access(filename, F_OK);
    if(temp != 0)   //文件不存在则创建
    {
        int ret = mkfifo(filename, 0644);
        if(ret == -1)
        {

            perror("mkfifo error:");
            exit(-1);
        }
    }
    

    pid_t pid = fork();     //fork创建一个新的进程
    if(pid < 0)
    {
        perror("fork error");
        _exit(-1);
    }
    else if(pid == 0)
    {
        cout <<"chile process" << endl;

        sleep(3);

        int fd = open(filename, O_RDONLY);
        if(fd == -1)
        {
            perror("open error:");
            _exit(-1);
        }
        char buffer[11];
        int readBytes = 0;
        while(1)
        {
            readBytes = read(fd, buffer, sizeof(buffer));
            if(readBytes < 0)
            {
                perror("read error:");
                _exit(-1);
            }
            cout << "buffer = " << buffer << endl;
            memset(buffer, 0, sizeof(buffer));
        }
        close(fd);
    }
    else
    {
        cout <<"parent process" << endl;
        
        int fd = open(filename, O_WRONLY);      //不用写0644，权限因为只在创建的时候有用
        if(fd == -1)
        {
            perror("open error:");
            _exit(-1);
        }
        const char * buf = "hello world";
        int writeBytes = 0;
        while(1)
        {
            writeBytes =  write(fd, buf, strlen(buf));
            cout << "writeBytes = " << writeBytes << endl;
            sleep(1);
        }
       
        close(fd);
    }

    while(1)
    {
        sleep(1);
    }


    return 0;
}